import { createStore, Store, useStore as useVuexStore } from 'vuex';
import type { IRootState, IStoreType } from './types';
import login from './login/login';
import system from './main/system/system';
import dashboard from './main/analysis/dashboard';
import { getPageListServer } from '@/service/main/system/system';

const store = createStore<IRootState>({
  state: () => {
    return {
      name: 'xjh',
      age: 18,
      allDepartment: [],
      allRole: [],
      allMenu: []
    };
  },
  mutations: {
    changeDepartment(state, list: any[]) {
      state.allDepartment = list;
    },
    changeRole(state, list: any[]) {
      state.allRole = list;
    },
    changeMenu(state, list: any[]) {
      state.allMenu = list;
    }
  },
  actions: {
    async getInitialDataAction({ commit }) {
      // 1.请求部门和角色数据
      const { data: departmentData } = await getPageListServer(
        '/department/list',
        {
          offset: 0,
          size: 1000
        }
      );
      const { data: roleData } = await getPageListServer('/role/list', {
        offset: 0,
        size: 1000
      });

      const { data: menuData } = await getPageListServer('/menu/list', {
        offset: 0,
        size: 10000
      });

      // 2. 保存数据
      commit('changeDepartment', departmentData.list);
      commit('changeRole', roleData.list);
      commit('changeMenu', menuData.list);
    }
  },
  modules: { login, system, dashboard }
});

export function setupStore() {
  store.dispatch('login/loadLocalLogin');
  store.dispatch('getInitialDataAction');
}

// 自己封装一个useStore 用约束一下我的类型操作
export function useStore(): Store<IStoreType> {
  return useVuexStore();
}

export default store;
